<template>
	<view class="view_list">
		<me-scroll :top="0" @getData="getData" ref="mescrollRef" :emptyInfo="emptyInfo">
			<block slot="list">
				<uni-collapse class="list_content" v-if="tableData.length" @change="handChangeCols">
					<uni-collapse-item v-for="(item,index) in tableData" :key="index" :open="true" :show-animation="true" class="list_item">
						<template v-slot:title>
							<me-section :title="item">
								<template #decoration>
									<radio class="icon_radio" :value="item" :checked="checkedVal.includes(item)" @click.stop="handleRadio(item)"/>
								</template>
							</me-section>
						</template>
						<viewItem :key="index" :data="allCodeInfo[item]" @del="goDel(item)" @print="goPrint(item)"/>
					</uni-collapse-item>
				</uni-collapse>
				<view class="page_bottomNav"></view>
				<me-loading ref="loading" />
			</block>
		</me-scroll>
		<view v-if="tableData.length" class="page_bottomNav_fixed">
			<view class="btn_list">
				<label class="radio_btn"  @click.stop="handleAllRadio">
					<radio class="icon_radio" value="allCkecked" :checked="isAllChecked" />
					<text class="radio_text">{{isAllChecked?'取消':''}}全选</text>
				</label>
			</view>
			<view class="btn_list">
				<button type="warn" @click="goDel()">移除</button>
				<button type="primary" @click="goPrint()">打印</button>
			</view>
		</view>
		<viewPrintMask ref="printMask" />
	</view>
</template>

<script>
import viewItem from './components/print/listItem.vue'
import viewPrintMask from './components/common/mask.vue'
import meScroll from '../../components/ui/me-scroll/index.vue';
import meLoading from '../../components/ui/me-loading/index.vue';
import meSection from '../../components/ui/me-section/index.vue';
import { getPrintCode } from '@/api/index'
import { showConfirm } from '../../utils/common'
var receiver;
export default {
	data() {
		return {
			params:{
				keyword:''
			},
			emptyInfo:{
				text:'暂无货品信息,请扫码添加'
			},
			isLoading: false,
			tableData: [],
			allCodeInfo:{},
			scrollRef:null,

			urovoPlatformModule:null,

			checkedVal:[]
		};
	},
	components:{
		viewItem,
		viewPrintMask,
		meScroll,
		meLoading,
		meSection
	},
	onLoad() {
		this.initData()
  },
	onShow() {},
	onUnload(){
		this.unRegisterBroadcast()
	},
	computed: {
		pageKey(){
			return 'codePrint'
		},
		isAllChecked(){
			return this.tableData.length === this.checkedVal.length
		}
	},
	methods: {
		initData(){
			if (!this.pageKey) {
				this.$modal.showToast('未找到标识');
				return false
			}
			// this.doAsync('1PMKGQ3CH/A','')
			// this.goPrint('25061884246009')
			try {
				this.main = plus.android.runtimeMainActivity()
				this.urovoPlatformModule = uni.requireNativePlugin("TH-PlatformSDK")
				var ws = plus.webview.currentWebview();
				plus.key.addEventListener("keydown", function(e) {
					if ([520,521,521].includes(e.keyCode)) {
						this.startScan()
					}
				})
				this.registerBroadcast()
			} catch (error) {
				
			}
			this.$nextTick(()=>{
				this.$refs['mescrollRef'].refresh()
			})
		},
		// 触发扫描
		startScan(){
			this.urovoPlatformModule.startScan();
		},
		// 停止扫描
		stopScan(){
			this.urovoPlatformModule.stopScan();
		},
		// 注册扫描
		registerBroadcast() {
			// 第一个参数 0:手动模式 1:连续模式
			// 第二个参数 0:广播输出模式 1:键盘输出模式
			this.urovoPlatformModule.setScanMode(0,0);
			// 播放声音
			const innerAudioContext = uni.createInnerAudioContext();
			// innerAudioContext.autoplay = true;
			innerAudioContext.src = '../../static/audio/scane_success.mp3';
			receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
				onReceive: doReceive
			});
			var that = this;
			var IntentFilter = plus.android.importClass('android.content.IntentFilter');
			var filter = new IntentFilter();
			filter.addAction("android.intent.ACTION_DECODE_DATA"); //监听扫描广播“urovo.rcv.message”  //android.intent.ACTION_DECODE_DATA
			// filter.addAction("com.ubx.scan.rfid");
			this.main.registerReceiver(receiver, filter); //注册监听
			// this.$modal.showToast('注册监听成功')
			function doReceive(context, intent) {
					plus.android.importClass(intent);
					var barcodeStr = intent.getStringExtra("barcode_string");
					// var barcodeStr = intent.getStringExtra("rfid_epc");
					console.log('扫描反馈',context,barcodeStr)
					innerAudioContext.stop();
					innerAudioContext.play();
					innerAudioContext.onError((res) => {
						console.log("InnerAudioContext()   errCode:"+res.errCode+"    errMsg:"+res.errMsg);
					});
					console.log("scan-barcode:"+barcodeStr);
					that.doAsync(barcodeStr) 
					// document.getElementsByClassName('text-box').innerText = barcodeStr;
			}
		},
		// 注销扫描
		unRegisterBroadcast() {
			this.main.unregisterReceiver(receiver);
		},
		async getData (mescroll = undefined) {
			try {
				this.isLoading = false
				const {scanCodes, scanInfos} = this.$store.getters || {}
				const lists = scanCodes[this.pageKey] || []
				this.tableData = JSON.parse(JSON.stringify(lists))
				this.allCodeInfo = JSON.parse(JSON.stringify(scanInfos[this.pageKey] || {}))
				this.closeLoading()
				mescroll && mescroll.endSuccess(lists.length);
			} catch (error) {
				console.log(error)
        this.closeLoading()
				mescroll && mescroll.endErr();
			}
		},
		closeLoading(){
			if (this.$refs.loading){
				this.$refs.loading.hide()
			};
			this.isLoading = false
		},
		// 扫描结束处理
		async doAsync (code,type = undefined) {
			const rules = /^\d{4}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$/
			const dateStr = '20' + (code || '').substring(0, 6)
			const codeLen = (code || '').length
			console.log('code',code,type)
			if(!code || !(rules.test(dateStr) && codeLen >= 14 && codeLen <= 16)){
			  this.$modal.confirm(this.$t('erp.productCodeError')+'!')
				return false
			}
			if(!type){
				const res = await this.$store.dispatch('setScanCode',{ pageKey:this.pageKey, code })
				if(!res.success){
					this.$modal.showToast(res.message);
					return false
				}
				console.log('res',res)
			}
			try {
				const {success,data,message} = await getPrintCode({goodsCode:code})
				if (!success) {
					this.$modal.showToast(message || '获取商品信息失败');
				}
				await this.$store.dispatch('setScanCode',{ pageKey:this.pageKey, code, info:data})
			} catch (error) {
				console.log('error',error)
			}
			this.$refs['mescrollRef'].refresh()
		},
		// 切换折叠面板
		handChangeCols(code){
			const codeIndexs = !code?[]:(Array.isArray(code)?code:[code])
			const codes = codeIndexs.map((item)=> this.tableData[item])
			codes.map((item)=>{
				const curInfo = this.allCodeInfo[item]
				if(!curInfo){
					this.doAsync(item,'updateInfo')
				}
			})
		},
		// 切换选择
		handleRadio(code){
			const index = this.checkedVal.findIndex((item)=> code === item)
			if(index === -1){
				this.checkedVal.push(code)
			}else{
				this.checkedVal.splice(index,1)
			}
		},
		// 全选切换
		handleAllRadio(){
			if(this.isAllChecked){
				this.checkedVal = []
			}else{
				this.checkedVal = this.tableData
			}
		},
		// 移除操作
		async goDel(code){
			if(!code && !this.checkedVal.length){
				this.$modal.showToast("请先勾选货品")
				return false
			}
			const vals = code?[code]:this.checkedVal
			showConfirm(`确定将${vals.length === 1?('货品('+vals[0]+')'):(vals.length +'个货品')}移除吗?`).then(async (res)=> {
				if (res.confirm) {
					await this.$store.dispatch('setScanCode',{ pageKey:this.pageKey, code:vals,type:'del' })
					this.$refs['mescrollRef'].refresh()
				}
			})
		},
		// 录入
		goPrint(code){
			if(!code && !this.checkedVal.length){
				this.$modal.showToast("请先勾选货品")
				return false
			}
			const vals = code?[code]:this.checkedVal
			this.$nextTick(()=>{
				console.log('去打印',vals)
				this.$refs['printMask'].open()
			})
		},
		goBack(){
			this.$tab.navigateBack({ data: 1 })
		},
		async goSearch (){
			console.log('search',this.params)
		},
		async clickTab (e){
			console.log('search',e,this.params)
			if (this.params.tabIndex != e.currentIndex) {
				this.params.tabIndex = e.currentIndex;
      }
		}
	}
	// onShareAppMessage(res) {
	// 	var title = '公告';
	// 	var path = '/otherpages/notice/list/list';
	// 	return {
	// 		title: title,
	// 		path: path,
	// 		success: res => {},
	// 		fail: res => {}
	// 	};
	// }
};
</script>

<style lang="scss">
.list_empty {
	position: relative;
	top: -50%;
	padding-top: 154px;
}
.view_list {
	.view_top{
		height: 100rpx;
	}
	.view_fixed{
		position: fixed;
		left: 0;
		top: 88rpx;
		z-index: 10;
		width: 100%;
		height: auto;
		background: #fff;
    box-shadow: 0px 2rpx 10rpx rgba(193, 193, 193, 0.2);
		.view_search{
			width: 100%;
			height: 110rpx;
			border-top: 1rpx solid #dcdcdc;
			border-bottom: 1rpx solid #dcdcdc;
			display: flex;
			align-items: center;
			justify-content: space-between;
			/deep/ .uni-searchbar{
				flex: 1;
			}
		}
		.view_tabs{
			width: 100%;
			height: 110rpx;
			padding: 15rpx 20rpx 15rpx;
			/deep/ .segmented-control--button{
				.segmented-control__item{
					border-radius: 50rpx;
					border-color: transparent !important;
					.segmented-control__text{
						color: #333 !important;
					}
					&.segmented-control__item--button--active{
						border:2rpx solid rgba(41, 121, 255, 1) !important;
						background-color: rgba(41, 121, 255, 0.3) !important;
						.segmented-control__text{
							color: rgba(41, 121, 255, 1) !important;
						}
					}
				}
			}
		}
	}
	/deep/ .list_content{
		padding: 30rpx;
		padding-top: calc(30rpx + 0rpx);
		background: transparent;
		.list_item{
			border-radius: 30rpx;
			background: #fff;
			overflow: hidden;
			.icon_radio{
				width: 40rpx;
				height: 40rpx;
				margin-right:20rpx;
				&::before{
					top: 50%;
					left: 50%;
					right: unset;
					bottom: unset;
					margin-top:unset;
					transform: translate(-50%,-50%);
				}
				.uni-radio-wrapper{
					width: 100%;
					height: 100%;
					.uni-radio-input{
						width: 100%;
						height: 100%;
						box-sizing: border-box;
					}
				}
			}
			&+.list_item{
				margin-top: 20rpx;
			}
		}

	}
}
.page_bottomNav{
	height: 100rpx;
}
.page_bottomNav_fixed{
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 5;
	width: 100%;
	height: 100rpx;
	background: #fff;
	border-top: 1rpx solid #dcdcdc;
	padding: 20rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 28rpx;
	color: #666;
	line-height: 36rpx;
	text-align: justify;
	.btn_list{
		display: flex;
		align-items: center;
	}
	/deep/ .radio_btn{
		display: flex;
		align-items: center;
		.icon_radio{
			width: 40rpx;
			height: 40rpx;
			&::before{
				top: 50%;
				left: 50%;
				right: unset;
				bottom: unset;
				margin-top:unset;
				transform: translate(-50%,-50%);
			}
			.uni-radio-wrapper{
				width: 100%;
				height: 100%;
				.uni-radio-input{
					width: 100%;
					height: 100%;
					box-sizing: border-box;
				}
			}
		}
		.radio_text{
			margin-left: 16rpx;
		}
	}
	button{
		min-width: 140rpx;
		height: 60rpx;
		font-size: 26rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: unset;
		margin-right: unset;
		&+button{
			margin-left: 20rpx;
		}
		&.error{
			background: red;
			color: #fff;
		}
	}
}
</style>
